package com.ddstation.waste_delivery.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import com.ddstation.common.service.DataDictionaryService;
import com.ddstation.exam.entity.DtHealthManageInstitutionGroupEntity;
import com.ddstation.exchange.service.DtHealthManageInstitutionGroupService;
import com.ddstation.instrument_disinfect.model.InstrumentDisinfectHeadResModel;
import com.ddstation.instrument_disinfect.model.InstrumentDisinfectResModel;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.util.getDateUtil;
import com.ddstation.waste_delivery.model.WasteDeliveryHeadResModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddstation.common.model.InvsCheckCommonSchParModel;
import com.ddstation.common.util.DateUtil;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.sewage.service.SewageService;
import com.ddstation.waste_delivery.model.WasteDeliveryDetailParModel;
import com.ddstation.waste_delivery.model.WasteDeliveryResModel;
import com.ddstation.waste_delivery.service.WasteDeliveryService;

@Controller
public class WasteDeliveryController {
	
	/**
	 * 查询诊所污水数据查询页面 跳转
	 * 
	 * @param
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_waste_delivery.do")
	public String wasteSeliveryInitEvent(
			Model model,
			HttpSession session) {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取当天
		Calendar cale = Calendar.getInstance();
		String lastday = format.format(cale.getTime());
		//取开始时间
		String firstday = getDateUtil.getFirstday(null);
		
		model.addAttribute("dtFrom", firstday); 	// 开始时间
		model.addAttribute("dtTo", lastday); 		// 当月的最后一天

		//一级医疗机构类别
		List<MaDataDictionaryEntity> typeFirstList = dataDictionaryService.getCodeList("institution_type_first");

		model.addAttribute("typeFirstList", typeFirstList);
		return "pc/waste_delivery/waste_delivery";
	}

	/**
	 * 数据查询接口
	 * 
	 * @param WasteDeliveryFormParModel  页面输入的条件
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_waste_delivery.do/load", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadWasteDeliveryListEvent(
			@RequestBody InvsCheckCommonSchParModel _in,
			HttpSession session) throws ParseException {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		
		// 日期check
		if ( StringUtils.isBlank(_in.getDtFrom()) || 
				StringUtils.isBlank(_in.getDtTo())){
			ret.put("errMsg", "没有输入查询日期！");
			return ret;
		}
		
        try {
        	 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        	 format.parse(_in.getDtFrom());
        	 format.parse(_in.getDtTo());
		} catch (Exception e) {
			ret.put("errMsg", "输日期格式必须为：yyyy-MM-dd");
			return ret;
		}
		
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
        // session中卫监所的基础信息传入service
        _in.setInvsInstitutionId(loginData.getInstitution().getId());
		// 查询实施
        List<WasteDeliveryResModel> datalist = wasteDeliveryService.searchWasteDeliveryList(_in);

		//查询全部父子机构信息
		Map<String, String> groupRelationship = getGroupRelationship();
		//定义重新组合集合
		List<WasteDeliveryResModel> comList=new ArrayList<>();
		Map<String, WasteDeliveryResModel> comMap = new HashMap<>();
		for(WasteDeliveryResModel data:datalist){
			//判断是否为子机构
			String belongId = groupRelationship.get(data.getInstitutionId());
			//父ID不存在则判断自己为父ID
			if(belongId == null){
				belongId = data.getInstitutionId();
			}else{
				//存在父ID剔除名称及机构ID
				data.setInstitutionName(null);
				data.setInstitutionId(null);
			}
			//获取当前ID数据
			WasteDeliveryResModel agoData = comMap.get(belongId);
			if(agoData == null){
				//数据不存在则添加数据
				comMap.put(belongId,data);
			}else{
				//数据存在累加数据
				Integer registryCnt = agoData.getRegistryCnt() + data.getRegistryCnt();
				Integer noAppealCnt = agoData.getNoAppealCnt() + data.getNoAppealCnt();
				agoData.setRegistryCnt(registryCnt);
				agoData.setNoAppealCnt(noAppealCnt);
				//替换名称为父ID对应名称
				if(data.getInstitutionName() != null){
					agoData.setInstitutionName(data.getInstitutionName());
				}
				//替换机构ID为父ID对应机构ID
				if(data.getInstitutionId() != null){
					agoData.setInstitutionId(data.getInstitutionId());
				}
				//存在一个状态为异常，则替换为异常
				if(data.getCheckSt() != 0){
					agoData.setCheckSt(-1);
				}
				//保存新累加的对象
				comMap.put(belongId,agoData);
			}
		}
		//遍历添加数据
		for (Map.Entry<String, WasteDeliveryResModel> entry : comMap.entrySet()) {
			//仅添加存在父机构数据
			if(entry.getValue() != null && entry.getValue().getInstitutionId() != null && entry.getValue().getInstitutionName() != null){
				comList.add(entry.getValue());
			}
		}

		ret.put("datalist",comList);
		
		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	//获取整理好的父子关系对照数据
	public Map<String,String> getGroupRelationship(){
		Map<String, String> map = new HashMap<>();
		List<DtHealthManageInstitutionGroupEntity> groupList = dtHealthManageInstitutionGroupService.selectAll();
		//遍历数据将子机构ID作为key，父机构ID作为value
		for(DtHealthManageInstitutionGroupEntity group:groupList){
			map.put(group.getChildInstitutionId(),group.getParentInstitutionId());
		}
		return map;
	}

	/**
	 * 查询医疗废弃物处置 明细数据接口
	 * 
	 * @param InstrumentDisinfectDetailFormParModel  页面输入的条件
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_waste_delivery.do/load_detail", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadWasteDeliveryDetailEvent(
			@RequestBody WasteDeliveryDetailParModel _in,
			HttpSession session) throws ParseException {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		_in.setInvsInstitutionId(loginData.getInstitution().getId());
		
		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),_in.getInstitutionId()) ){
			ret.put("errMsg", "没有访问权限！");
			return ret;
		}
		
		// 输入参数check
		if ( StringUtils.isBlank(_in.getInstitutionId()) && 
				( StringUtils.isBlank(_in.getDtFrom()) && StringUtils.isBlank(_in.getDateYm()))
			){
			ret.put("errMsg", "系统出错，没有输入参数！");
			return ret;
		}
		
		if ( StringUtils.isNotBlank(_in.getDateYm())   ){
			String[] beginEndDate = DateUtil.getBeginEndDate(_in.getDateYm());
			if ( beginEndDate == null ){
				ret.put("errMsg", "系统出错，传入参数：年月错误！");
				return ret;
			}
			_in.setDtFrom(beginEndDate[0]);
			_in.setDtTo(beginEndDate[1]);
		}
		//查询机构全部子ID
		DtHealthManageInstitutionGroupEntity entity = new DtHealthManageInstitutionGroupEntity();
		entity.setParentInstitutionId(_in.getInstitutionId());
		List<DtHealthManageInstitutionGroupEntity> dtHealthManageInstitutionGroupList = dtHealthManageInstitutionGroupService.select(entity);

		//设置机构ID集合，必定存在父机构ID
		List<String> institutionIdList = new ArrayList<>();
		institutionIdList.add(_in.getInstitutionId());
		if(dtHealthManageInstitutionGroupList != null && dtHealthManageInstitutionGroupList.size() > 0){
			//存在子ID则全部加入in条件查询
			for(DtHealthManageInstitutionGroupEntity dtHealthManageInstitutionGroup:dtHealthManageInstitutionGroupList){
				institutionIdList.add(dtHealthManageInstitutionGroup.getChildInstitutionId());
			}
		}
		_in.setInstitutionIdList(institutionIdList);
        //去除原机构ID条件
        _in.setInstitutionId(null);
		//数据查询
		List<WasteDeliveryHeadResModel> datalist = wasteDeliveryService.searchInstitutionSewageDetailList(_in);
		//替换展示 机构/科室 名称
		for(WasteDeliveryHeadResModel data:datalist){
			if(institutionIdList.get(0).equals(data.getInstitutionId())){
				data.setInstitutionShortName(data.getInstitutionName());
			}
		}
		
        // 查询实施
		ret.put("datalist",datalist);

		ret.put("errcode", 0);
		ret.put("errMsg", "");
		
		return ret;
	}
	
	@Inject private WasteDeliveryService wasteDeliveryService;
	@Inject private SewageService sewageService;
	@Inject private DtHealthManageInstitutionGroupService dtHealthManageInstitutionGroupService;
	@Inject private DataDictionaryService dataDictionaryService;
}
